//
//  SQFMDBManager.m
//  markmap
//
//  Created by 甘世清 on 2024/5/26.
//

#import "SQFMDBManager.h"
#import <JQFMDB/JQFMDB.h>
@implementation SQFMDBManager

/// 存储会话列表
/// - Parameter model: 列表模型
+(BOOL)SQ_addListIM:(IMListModel*)model{
    JQFMDB *db = [JQFMDB shareDatabase];
      if ([db jq_isExistTable:[SQFMDBManager SQ_getFMDBName]]) { //有表
        [db jq_alterTable:[SQFMDBManager SQ_getFMDBName] dicOrModel:[IMListModel class]];
         NSString * string = [NSString stringWithFormat:@"where roomId = '%@'",model.roomId];
         NSArray * moarray = [db jq_lookupTable:[SQFMDBManager SQ_getFMDBName] dicOrModel:[IMListModel class] whereFormat:string]; //根据id查数据
          if (moarray.count > 0) { //如果有值,那就把服务器没返回的值存进去
              IMListModel * mo = moarray.lastObject;
              if (![model.content isNotEmpty] && model.msgType != -1) {
                  model.content = mo.content;
              }
              if (![model.time isNotEmpty]) { //如果需要存储的模型时间戳是空的,那就复制老时间戳给新模型
                  model.time = mo.time;
              }
          }
           [db jq_deleteTable:[SQFMDBManager SQ_getFMDBName] whereFormat:string];
       } else {
           //创建表
           [db jq_createTable:[SQFMDBManager SQ_getFMDBName] dicOrModel:[IMListModel class]];
       }
       if (![model.time isNotEmpty]) { //如果新的老的都是空的,那就给当前时间
           model.time = [NSString SQ_currentTime];
       }
       BOOL isok =   [db jq_insertTable:[SQFMDBManager SQ_getFMDBName] dicOrModel:model];
       //存储成功就发送通知
       [[NSNotificationCenter defaultCenter] postNotificationName:@"IMListModel" object:model];
       return isok;
   }
 
//聊天列表读取
+(NSArray*)SQ_IMAcquire{
    JQFMDB *db = [JQFMDB shareDatabase];
    NSArray *personArr = [db jq_lookupTable:[SQFMDBManager SQ_getFMDBName] dicOrModel:[IMListModel class] whereFormat:@"order by time desc"];
    return personArr;
}


/// 根据查询的房间id返回一个房间模型
/// - Parameter roomID: 房间id
+(IMListModel*)SQ_roomIDGetIMListModel:(NSString*)roomID{
    NSString * string = [NSString stringWithFormat:@"where roomId = %@",roomID];
    JQFMDB *db = [JQFMDB shareDatabase];
    NSArray * moarray = [db jq_lookupTable:[SQFMDBManager SQ_getFMDBName] dicOrModel:[IMListModel class] whereFormat:string];
    if (moarray.count > 0) {
        return moarray.firstObject;
    }
    return [IMListModel new];
}
/// 根据查询的用户id返回一个房间模型
/// - Parameter roomID: 房间id
+(IMListModel*)SQ_userIdGetIMListModel:(NSString*)peopleId{
    NSString * string = [NSString stringWithFormat:@"where peopleId = %@",peopleId];
    JQFMDB *db = [JQFMDB shareDatabase];
    NSArray * moarray = [db jq_lookupTable:[SQFMDBManager SQ_getFMDBName] dicOrModel:[IMListModel class] whereFormat:string];
    if (moarray.count > 0) {
        return moarray.firstObject;
    }
    return [IMListModel new];
}

/// 根据房间id删除整个数据
/// - Parameter roomID: 房间id
+(BOOL)SQ_deletet:(NSString*)roomID{
    IMListModel * mo = [SQFMDBManager SQ_roomIDGetIMListModel:roomID];
    if (![mo.roomId isNotEmpty]) {
        return YES;
    }
    JQFMDB *db = [JQFMDB shareDatabase];
    if ([db jq_isExistTable:[SQFMDBManager SQ_getFMDBName]]) {
        //删除里面的模型数据
        NSString * name = [NSString stringWithFormat:@"IM%@",roomID];
        if ([db jq_isExistTable:name]) {
            [db jq_deleteTable:name];
        }
        //删除外面的列表
        NSString * string = [NSString stringWithFormat:@"where roomId = '%@'",roomID];
      BOOL isok =  [db jq_deleteTable:[SQFMDBManager SQ_getFMDBName] whereFormat:string];
        return isok;
    }
    return  NO;
}


/// 存储消息列表接口
/// - Parameter model: 消息模型
+(BOOL)SQ_addListIMMessage:(IMMessageModel*)model{
    //先查询是否存在列表immodel
    IMListModel * mo = [SQFMDBManager SQ_roomIDGetIMListModel:model.roomId];
    mo.noReadCount = model.noReadCount;
    mo.content = model.content;
    mo.msgType = model.msgType;
    mo.time = model.time;
   
    if ([model.froms isEqualToString:[UserModel share].userid]) {
        //是自己的
        model.portrait = [UserModel share].portrait;
        model.name = [UserModel share].name;
        model.sendType = NO;
    } else {
        if (![mo.roomId isNotEmpty]) {
            NSDictionary * ext = [[NSDictionary alloc]initWithDictionary:[model.ext mj_JSONObject]];
            mo.roomId = model.roomId;
            mo.portrait = [NSString stringWithFormat:@"%@",[ext objectForKey:@"portrait"]];
            mo.name = [NSString stringWithFormat:@"%@",[ext objectForKey:@"name"]];
            mo.peopleId = [NSString stringWithFormat:@"%@",[ext objectForKey:@"peopleId"]];
        }
        model.portrait = mo.portrait;
        model.name = mo.name;
        model.sendType = YES;
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); //加个震动
    }
    [SQFMDBManager SQ_addListIM:mo];
    
    JQFMDB *db = [JQFMDB shareDatabase];
    NSString * name = [NSString stringWithFormat:@"IM%@",model.roomId];
    if ([db jq_isExistTable:name]) {
        [db jq_alterTable:name dicOrModel:[IMMessageModel class]];
        NSString * string = [NSString stringWithFormat:@"where IMId = '%@'",model.IMId];
        [db jq_deleteTable:name whereFormat:string];
    } else {
      [db jq_createTable:name dicOrModel:[IMMessageModel class]];
       
    }
    BOOL isok =  [db jq_insertTable:name dicOrModel:model];
    DTLog(@"消息存储状态--- %d --- %@",isok,[NSString SQ_currentTime]);
    if (isok) {
        //存储成功就发送通知
        [IMMessageManager SQ_showMessage:model];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"IMMessageModel" object:[model mj_JSONObject]];
    }  
    return  isok;
}

+(NSArray*)SQ_UserAcquireID:(NSString*)roomId size:(NSInteger)size page:(NSInteger)page{
    JQFMDB *db = [JQFMDB shareDatabase];
    NSString * where = [NSString stringWithFormat:@"order by time desc, IMId desc limit %ld, %ld", (long)page,(long)size + 300];
    NSArray *personArr = [db jq_lookupTable:[NSString stringWithFormat:@"IM%@",roomId] dicOrModel:[IMMessageModel class] whereFormat:where];
    return [personArr sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        IMMessageModel * model1 = obj1;
        IMMessageModel* mode2 = obj2;
        if ([model1.time intValue] > [mode2.time intValue]) {
            return NSOrderedDescending;//降序
        } else {
            return NSOrderedAscending;//升序
        }
    }];
}
/// 根据消息id来判断是否该消息已存储
/// - Parameter model: 模型
+(BOOL)SQ_messageModel:(IMMessageModel*)model{
    NSString * string = [NSString stringWithFormat:@"where IMId = %@",model.IMId];
    JQFMDB *db = [JQFMDB shareDatabase];
    NSArray * moarray = [db jq_lookupTable:[NSString stringWithFormat:@"IM%@",model.roomId] dicOrModel:[IMMessageModel class] whereFormat:string];
    if (moarray.count > 0) {
        return YES;
    }
    return NO;
}


/// 根据房间id删除整个数据
/// - Parameter roomID: 房间id
+(BOOL)SQ_deletetMessage:(NSString*)roomID{
    
    JQFMDB *db = [JQFMDB shareDatabase];
    NSString * name = [NSString stringWithFormat:@"IM%@",roomID];
    if ([db jq_isExistTable:name]) {
        //删除里面的模型数据
        BOOL isok =   [db jq_deleteTable:name];
        return isok;
     }
    return  YES;
}

+(NSString*)SQ_getFMDBName{
    //根据用户id拼接的一个列表名字 唯一
    return [NSString stringWithFormat:@"MapUser_%@",[UserModel share].userid];
}


@end
